<template>
  <view class="relative bg-white order-list">
    <nav-bar color="white" bg-color="black" title="订单" show-back></nav-bar>
    <u-row gutter="10rpx" customStyle="padding:8rpx;">
      <u-col span="3">
        <u-subsection
          :list="subsectionList"
          mode="subsection"
          :current="curNow"
          font-size="9rpx"
          active-color="var(--kui-color-theme)"
          @change="handleChange"
        ></u-subsection>
        <!-- <uni-segmented-control
          :current="curNow"
          :values="subsectionList"
          style-type="button"
          active-color="var(--kui-color-theme)"
        /> -->
      </u-col>
      <u-col span="3">
        <uni-datetime-picker v-model="filterPam.range" type="daterange" @change="selectDateChange" />
      </u-col>
      <u-col span="3">
        <u-search
          shape="square"
          placeholder="请输入完整订单号"
          v-model="filterPam.buffetOrderId"
          :actionStyle="{
            background: 'var(--kui-color-theme)',
            'max-height': '20rpx',
            height: '20rpx',
            'border-radius': '3rpx',
            'border-top-left-radius': '0',
            'border-bottom-left-radius': '0',
            color: 'white',
            display: 'flex',
            'justify-content': 'center',
            'align-items': 'center',
            padding: '0 5rpx',
          }"
          search-icon-size="15rpx"
          clear
          @custom="getPageData(true)"
        ></u-search>
      </u-col>
      <u-col span="1">
        <u-button type="info" color="lightgrey" @click="resetFilter" custom-style="height:20rpx">重置</u-button>
      </u-col>
    </u-row>
    <u-row>
      <view class="px-12rpx w-full box-border">
        <view class="statistics-cards">
          <view class="stat-card">
            <text class="stat-label">订单总数</text>
            <text class="stat-value">{{ orderMoneData.orderNum || 0 }}单</text>
          </view>
          <view class="stat-card">
            <text class="stat-label">实收金额</text>
            <text class="stat-value">{{ orderMoneData.amountcollected || 0 }}元</text>
          </view>
          <view class="stat-card">
            <text class="stat-label">补贴金额</text>
            <text class="stat-value">{{ orderMoneData.mealAllowance || 0 }}元</text>
          </view>
          <view class="stat-card">
            <text class="stat-label">订单金额</text>
            <text class="stat-value">{{ orderMoneData.money || 0 }}元</text>
          </view>
        </view>
        
        
        <uni-table :loading="pageStatus.loading" class="table-height" stripe emptyText="暂无更多数据" :border="true">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th align="center" class="fixed-left">序号</uni-th>
            <uni-th align="center">订单ID</uni-th>
            <uni-th align="left">订单人</uni-th>
            <uni-th align="left">就餐方式</uni-th>
            <uni-th align="left">数量</uni-th>
            <uni-th align="left">订单金额（元）</uni-th>
            <uni-th align="left">补贴金额（元）</uni-th>
            <uni-th align="left">实收金额（元）</uni-th>
            <uni-th align="left">支付方式</uni-th>
            <uni-th align="left">支付状态</uni-th>
            <uni-th align="left">订单状态</uni-th>
            <uni-th align="left">订单退款状态</uni-th>
            <uni-th align="left">支付时间</uni-th>
            <uni-th align="left" class="fixed-right">操作</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in orderList" :key="item.buffetOrderId">
            <uni-td align="center" bg-color="white" :fixed="true" >{{ index + 1 }}</uni-td>
            <uni-td align="center">{{ item.buffetOrderId }}</uni-td>
            <uni-td align="center">{{ item.customerInformationName }}</uni-td>
            <uni-td align="center">{{ diningStyles[item.diningStyle] || "-" }}</uni-td>
            <uni-td align="center">{{ item.foodNum }}</uni-td>
            <uni-td align="center">{{ item.money }}</uni-td>
            <uni-td align="center">{{ item.mealAllowance }}</uni-td>
            <uni-td align="center">{{ item.amountcollected }}</uni-td>
            <uni-td align="center">{{ payTypes[item.payType] || "-" }}</uni-td>
            <uni-td align="center">{{ payStatus[item.payStatus] || "-" }}</uni-td>
            <uni-td align="center">{{ orderStatus[item.orderStatus] }}</uni-td>
            <uni-td align="center">{{ refundStatus[item.refundStatus] }}</uni-td>
            <uni-td align="center">{{ item.payTime }}</uni-td>
            <uni-td align="center" customClass="tdata" bg-color="white" :fixed="true">
              <view class="flex bg-white">
                <u-button type="primary" @click="toDetails(item)">查看</u-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="pagination-box">
          <uni-pagination
            show-icon
            :page-size="filterPam.size"
            :current="filterPam.current"
            :total="filterPam.total"
            @change="pageChange"
          />
        </view>
      </view>
    </u-row>
  </view>
</template>
<script lang="ts" setup>
import { onPullDownRefresh } from "@dcloudio/uni-app";
import { debounce } from "@kingon/app-tools";
import dayjs from "dayjs";
import { reactive, ref, onMounted } from "vue";
import { getBuffetOrderList, buffetOrderListMone } from "@/api";

const curNow = ref(0);

const diningStyles = {
  1: "送餐",
  2: "堂食",
  3: "自提",
};

const payTypes = {
  1: "余额",
  2: "微信",
  3: "支付宝",
  4: "现金",
  5: "套餐",
  6: "刷卡",
  7: "货到付款",
};

const payStatus = {
  0: "未支付",
  1: "已支付",
};

// 订单状态（1未出单2已出单、未领 3已领餐、4已送达5逾期6退单7已评论8已派单9待派单10已取消）
const orderStatus = {
  1: "未出单",
  2: "已出单",
  3: "已领餐",
  4: "已送达",
  5: "逾期",
  6: "退单",
  7: "已评论",
  8: "已派单",
  9: "待派单",
  10: "已取消",
};

// 退款状态(0未退款1已退款2部分退款)
const refundStatus = {
  0: "未退款",
  1: "已退款",
  2: "部分退款",
};

const pageStatus = reactive({
  loading: false,
});

const filterPam = reactive({
  range: [],
  buffetOrderId: "",
  createTimeStartTime: "",
  createTimeEndTime: "",
  current: 1,
  size: 10,
  total: 0,
});

const orderList = ref([]);

const pageChange = (e) => {
  filterPam.current = e.current;
  getPageData();
};

const getPageData = async (isReload = false) => {
  if (isReload) {
    filterPam.current = 1;
  }

  pageStatus.loading = true;
  try {
    const pam = {
      // orderStatus: 3,
      orderType: 1,
      // dcsource: 8,  // 下单方式（1商家app2小程序4家庭版app5送餐人员app、6电话下单 7日照PC端8消费机）
      ...filterPam,
    };
    const { data, success } = await getBuffetOrderList(pam);
    console.log("getBuffetOrderList:", data);
    if (!success) throw new Error("获取数据失败");
    orderList.value = data.records;
    filterPam.total = data.total;
    pageStatus.loading = false;
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

const toDetails = (item) => {
  uni.navigateTo({
    url: "./order-details?id=" + item.buffetOrderId,
  });
};



//---
const fullDate = "YYYY-MM-DD HH:mm:ss";
const sourceSubsection = [
  {
    name: "今日",
    value: [dayjs().startOf("day").format(fullDate), dayjs().endOf("day").format(fullDate)],
  },
  {
    name: "本周",
    value: [dayjs().startOf("week").format(fullDate), dayjs().endOf("week").endOf("day").format(fullDate)],
  },
  {
    name: "本月",
    value: [dayjs().startOf("month").format(fullDate), dayjs().endOf("month").endOf("day").format(fullDate)],
  },
];
const subsectionList = sourceSubsection.map((v) => v.name);
const handleChange = (e) => {
  try {
    [filterPam.createTimeStartTime, filterPam.createTimeEndTime] = sourceSubsection[e].value;
    getPageData(true);
    getOrderMone();
  } catch (error) {
    console.error(error);
  }
};

const selectDateChange = (e) => {
  const [start, end] = e;
  filterPam.createTimeStartTime = dayjs(start).format(fullDate);
  filterPam.createTimeEndTime = dayjs(end).endOf("day").format(fullDate);
  getPageData(true);
  getOrderMone();
};

const resetFilter = () => {
  filterPam.range = [];
  filterPam.buffetOrderId = "";
  filterPam.createTimeStartTime = "";
  filterPam.createTimeEndTime = "";
  filterPam.current = 1;
  getPageData(true);
  getOrderMone();
};



const orderMoneData = ref({
  amountcollected: 0,
  mealAllowance: 0,
  governmentSubsidies: 0,
  enterpriseSubsidies: 0,
  num: 0,
  orderNum: 0,
  personNumber: 0,
  subsidyNum: 0,
  money: 0
});

// 获取订单统计信息
const getOrderMone = async () => {
  try {
    const pam = {
      orderStatus: 3,
      orderType: 1,
      ...filterPam,
    };
    const { data, success } = await buffetOrderListMone(pam);
    console.log("getOrderMone:", data);
    if (!success) throw new Error("获取数据失败");
    orderMoneData.value = data;
  } catch (error) {
    console.error(error);
  }
};

// handleChange(0);
onMounted(() => {
  handleChange(0);
});
</script>
<style lang="scss" scoped>
.order-list {
  ::v-deep .u-search__content {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
    margin-right: -10px;
    height: 20rpx;

    .u-search__content__icon {
      display: none;
    }

    .uni-input-input {
      height: 20rpx;
    }
  }
}

.fixed-left {
  position: sticky;
  background-color: white;
  left: 0;
}

.fixed-right {
  position: sticky;
  right: 0;
  background-color: white;
}

.table-height {
  max-height: 70vh;
}

.pagination-box {
  padding: 10rpx;
  display: flex;
  flex-direction: row;
  justify-content: right;
  position: sticky;
  bottom: 0;
  background: white;
}

.statistics-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
  
  .stat-card {
    background: #f8f9fa;
    border-radius: 8rpx;
    padding: 7rpx 10rpx;
    flex: 1;
    margin: 0 5rpx;
    display: flex;
    flex-direction: column;
    align-items: start;
    
    .stat-label {
      font-size: 8rpx;
      color: #666;
      margin-bottom: 4rpx;
    }
    
    .stat-value {
      font-size: 12rpx;
      color: #333;
      font-weight: bold;
    }
  }
}
</style>
